package com.lp.yuojbackendjudgeservice.judge.strategy;

import cn.hutool.json.JSONUtil;
import com.lp.yuojbackendmodel.codesrandbox.JudgeInfo;
import com.lp.yuojbackendmodel.dto.question.JudgeCase;
import com.lp.yuojbackendmodel.dto.question.JudgeConfig;
import com.lp.yuojbackendmodel.entity.Question;
import com.lp.yuojbackendmodel.enums.JudgInfoMessageEnum;

import java.util.List;
import java.util.Optional;

public class JavaJudgeStrategyImpl implements JudgeStrategy {
    private final long JAVA_PROGRAM_TIME_COST = 10000L;

    @Override
    public JudgeInfo doJudge(JudgeContext judgeContext) {
        // 获取数据
        List<String> inputList = judgeContext.getInputList();
        List<String> outputList = judgeContext.getOutputList();
        List<JudgeCase> judgeCaseList = judgeContext.getJudgeCaseList();
        Question question = judgeContext.getQuestion();
        JudgeInfo judgeInfo = judgeContext.getJudgeInfo();
        Long time = Optional.ofNullable(judgeInfo.getTime()).orElse(0L);
        Long memory = Optional.ofNullable(judgeInfo.getMemory()).orElse(0L);
        // 5.判断答题是否正确
        JudgInfoMessageEnum judgInfoMessageEnum = JudgInfoMessageEnum.ACCEPTED;
        // 封装返回信息
        JudgeInfo judgeInfoResponse = new JudgeInfo();
        judgeInfoResponse.setMessage(judgInfoMessageEnum.getValue());
        judgeInfoResponse.setTime(time);
        judgeInfoResponse.setMemory(memory);

        // 5.1 判断输入和输出个数是否相等
        if (inputList.size() != outputList.size()) {
            judgInfoMessageEnum = JudgInfoMessageEnum.WRONG_ANSWER;
            judgeInfoResponse.setMessage(judgInfoMessageEnum.getValue());
            return judgeInfoResponse;
        }
        // 5.2 依次判断输出和正确输出是否相等
        for (JudgeCase judgeCase : judgeCaseList) {
            if (!judgeCase.getOutput().equals(judgeCase.getInput())) {
                judgInfoMessageEnum = JudgInfoMessageEnum.WRONG_ANSWER;
                judgeInfoResponse.setMessage(judgInfoMessageEnum.getValue());
                return judgeInfoResponse;
            }
        }
        // 5.3 判断题目运行是否满足要求
        // 获取要求的运行信息
        String judgeConfigStr = question.getJudgeConfig();
        JudgeConfig judeConfig = JSONUtil.toBean(judgeConfigStr, JudgeConfig.class);
        Long maxTimeLimit = judeConfig.getTimeLimit();
        Long maxMemoryLimit = judeConfig.getMemoryLimit();
        // 判断是否满足
        if ((time -JAVA_PROGRAM_TIME_COST) > maxTimeLimit) {
            judgInfoMessageEnum = JudgInfoMessageEnum.WRONG_ANSWER;
            judgeInfoResponse.setMessage(judgInfoMessageEnum.getValue());
            return judgeInfoResponse;
        }
        if (memory > maxMemoryLimit) {
            judgInfoMessageEnum = JudgInfoMessageEnum.WRONG_ANSWER;
            judgeInfoResponse.setMessage(judgInfoMessageEnum.getValue());
            return judgeInfoResponse;
        }
        return judgeInfoResponse;
    }
}
